import type { RouteRecordRaw } from 'vue-router'
import type { IBreadcrumb } from '../components/navHeader/type'
let firtMenu: any
export function mapMenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []
  //先默认获取所有的router
  const allRoute: RouteRecordRaw[] = []
  const routeFile = require.context('../router/main', true, /\.ts$/)
  routeFile.keys().forEach((key) => {
    const route = require('../router/main' + key.split('.')[1])
    allRoute.push(route.default)
  })
  //动态获取匹配路由
  const _recorseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = allRoute.find((route) => route.path === menu.url)
        if (!firtMenu) firtMenu = route
        if (route) routes.push(route)
      } else {
        _recorseGetRoute(menu.children)
      }
    }
  }
  _recorseGetRoute(userMenus)
  return routes
}

export function pathMapBreadcrumb(
  userMenu: any[],
  currentPath: string
): IBreadcrumb[] {
  const breadcrumbs: IBreadcrumb[] = []
  pathMapToMenu(userMenu, currentPath, breadcrumbs)
  return breadcrumbs
}

export function pathMapToMenu(
  userMenu: any[],
  currentPath: string,
  breadcrumbs?: IBreadcrumb[]
): any {
  for (const menu of userMenu) {
    if (menu.type === 2) {
      if (menu.url === currentPath) {
        return menu
      }
    } else if (menu.type === 1) {
      const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
      if (findMenu) {
        //breadcrumbs？.push({ name: menu.name, path: menu.url })
        breadcrumbs?.push({ name: menu.name, path: menu.url })
        breadcrumbs?.push({ name: findMenu.name, path: findMenu.url })
        return findMenu
      }
    }
  }
}

//获取动态路由权限
export function mapMenusToPermission(mapMenus: any[]) {
  const permission: string[] = []

  const _Getpermission = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 1 || menu.type === 2) {
        _Getpermission(menu.children ?? [])
      } else if (menu.type === 3) {
        permission.push(menu)
      }
    }
  }
  _Getpermission(mapMenus)

  return permission
}
//获取叶子节点id
export function mapMenusToId(menusList: any[]): number[] {
  const menusId: number[] = []
  const _mapMenusToId = (menusList: any[]) => {
    for (const list of menusList) {
      if (list.children) {
        _mapMenusToId(list.children)
      } else {
        menusId.push(list.id)
      }
    }
  }
  _mapMenusToId(menusList)
  //console.log(menusId)
  return menusId
}

export { firtMenu }
